package cn.wm.client;

import cn.hutool.log.Log;
import cn.hutool.log.StaticLog;
import cn.wm.codec.MessageDecoder;
import cn.wm.codec.MessageEncoder;
import cn.wm.constant.ProtocolConstants;
import cn.wm.server.LoginAuthRespHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.timeout.ReadTimeoutHandler;

/**
 * Client
 *
 * @author wm
 * @version 1.0
 * 2021/6/25 14:04
 **/
public class Client {

    private final static Log log = StaticLog.get();

    public static void main(String[] args) {
        EventLoopGroup worker = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(worker)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.SO_KEEPALIVE, Boolean.TRUE)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            pipeline.addLast("frameDecoder", new MessageDecoder());
                            pipeline.addLast("frameEncoder", new MessageEncoder());
                            pipeline.addLast("readTimeoutHandler", new ReadTimeoutHandler(50));
                            //<todo>
                            pipeline.addLast("loginAuthReqHandler", new LoginAuthReqHandler());
                            pipeline.addLast("heartBeatReqHandler",new HeartBeatReqHandler());
                            pipeline.addLast(new ClientHandler());
                        }
                    });
            ChannelFuture sync = bootstrap.connect(ProtocolConstants.SERVER_URL, ProtocolConstants.SERVER_PORT).sync();
            log.info("Client start... connect server url: {} , port: {}", ProtocolConstants.SERVER_URL, ProtocolConstants.SERVER_PORT);
            sync.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            worker.shutdownGracefully();
        }
    }
}
